package com.alkaid.user.service.impl;

import com.alkaid.commons.msg.MsgDefinition;
import com.alkaid.commons.entity.Authority;
import com.alkaid.commons.ex.AuthorityInsertException;
import com.alkaid.commons.ex.AuthorityNotFoundException;
import com.alkaid.commons.utils.SnowflakeIdWorker;
import com.alkaid.user.mapper.AuthorityMapper;
import com.alkaid.user.service.AuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Kylin
 */
@Service
public class AuthorityServiceImpl implements AuthorityService {

    private AuthorityMapper authorityMapper;
    @Autowired
    public void setAuthorityMapper(AuthorityMapper authorityMapper) {
        this.authorityMapper = authorityMapper;
    }

    @Override
    public List<Authority> getAuthoritiesByUserId(Long userId) throws AuthorityNotFoundException {
        if (userId == null) {
            return null;
        }
        List<Authority> authorities = authorityMapper.findAuthorityByUserId(userId);
        if (authorities == null) {
            throw new AuthorityNotFoundException(MsgDefinition.AUTHORITY_NOTFOUND);
        }
        return authorities;
    }

    @Override
    public void addAuthorityForReg(Long userId, String username) throws AuthorityInsertException {
        Authority authority = initAddAuthority(userId, username);
        authority.setRoleId(1);
        Date date = new Date(4765104000000L);
        authority.setExpiredTime(date);
        Integer result = authorityMapper.insertAuthority(authority);
        if (result < 1) {
            throw new AuthorityInsertException(MsgDefinition.AUTHORITY_ADD_REG_FAILED);
        }
    }

    private Authority initAddAuthority(Long userId, String username){
        Authority authority = new Authority();
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 1);
        Long id = idWorker.nextId();
        authority.setId(id);
        authority.setUserId(userId);
        authority.setCreatedUser(username);
        authority.setCreatedTime(new Date());
        authority.setModifiedUser(username);
        authority.setModifiedTime(new Date());
        return authority;
    }
}
